const convertArrayToTreeArray = (array, format) => {
  let ret = [];
  let parent = format.parent;
  let id = format.id;
  array.forEach(item => {
    item._expand = true;
    item.children = item.children || [];
    let root = array.find(m => {
      return item[parent] === m[id];
    });
    if (!root) {
      ret.push(item);
    } else {
      root.children = root.children ? [...root.children, item] : [item];
    }
  });
  return ret;
};

const dateFormatter = (formatter, date) => {
  if (date === null || typeof date === 'undefined') {
    return '';
  }
  date = date ? new Date(date) : new Date();
  const Y = date.getFullYear() + '';
  const M = date.getMonth() + 1;
  const D = date.getDate();
  const H = date.getHours();
  const m = date.getMinutes();
  const s = date.getSeconds();
  return formatter.replace(/YYYY|yyyy/g, Y)
    .replace(/YY|yy/g, Y.substr(2, 2))
    .replace(/MM/g, (M < 10 ? '0' : '') + M)
    .replace(/dd/g, (D < 10 ? '0' : '') + D)
    .replace(/HH|hh/g, (H < 10 ? '0' : '') + H)
    .replace(/mm/g, (m < 10 ? '0' : '') + m)
    .replace(/ss/g, (s < 10 ? '0' : '') + s);
};

const transitionEndEventListener = (el, fn) => {
  el.addEventListener('transitionend', function transitionEndHandler () {
    el._transitionEndHandler = transitionEndHandler;
    el.removeEventListener('transitionend', el._transitionEndHandler);
    el.remove();
    if (fn && typeof fn === 'function') {
      fn();
    }
  });
};

const pop = (VueComponent, prop, vm) => {
  let component = new VueComponent({
    parent: vm,
    propsData: prop
  }).$mount();
  let $el = component.$el;
  document.body.appendChild($el);
  return component;
};

const attr = (obj, prop, value) => {
  if (typeof value === 'undefined') {
    if (/\./.test(prop)) {
      let props = prop.split('.');
      let ret = obj;
      for (let i = 0; i < props.length; i++) {
        ret = ret[props[i]];
        if (typeof ret === 'undefined') {
          break;
        }
      }
      return ret;
    }
    return obj[prop];
  } else {
    let props = prop.split('.');
    props.reduce((prev, curr, currentIndex, array) => {
      prev[curr] = prev[curr] || {};
      if (currentIndex === array.length - 1) {
        prev[curr] = value;
      }
      return prev[curr];
    }, obj);
  }
};

export { convertArrayToTreeArray, dateFormatter, pop, transitionEndEventListener, attr };
